<?
class Customer extends DB
{
	function __construct($other_conn=null)
	{
		parent::__construct(Tcustomer,$other_conn);
		$this->table=Tcustomer;
	}
	function update_last_login_time($id)
	{	
		$vardate=date('Y-m-d H:i:s');
		$sqlString = "UPDATE $this->table SET ";
		$sqlString .= " login_count=login_count+1, ";
		$sqlString .= " last_login_time='". $vardate."'";
		$sqlString .= " WHERE id = '" . $id."'";
		return $this->exec($sqlString);
		echo $sqlString;
	}
	function check_sign($user,$pwd,$type='username',$encrypt=true)
	{	
		$result = $this->query("SELECT * FROM $this->table WHERE $type = '" . $user . "'");
		$row = $this->fetch_row($result);
		if(empty($row)) return 8; // 账号不存在
		$db_password=($encrypt)?sha1($pwd):$pwd;
		if($db_password==$row['password']){
			if($row['is_enabled']==1) return 1;
			else return 4; // banned, 账号禁用
		}
		return 0;
	}
	function credit($id,$credit=0) // need change later
	{
		return $this->exec("UPDATE $this->table set credit = credit+$credit where id =".$id." limit 1 ");
	}
	function add_point_by_order($ref_no)
	{
		global $arrcurrency;
		$sales_order=new DB(Tsales_order);
		$point=new DB(Tpoint);

		$order = $sales_order->get_row($ref_no,'ref_no');
		$tem_currency_id=$order['currency_id'];
		$tem_rate=$arrcurrency[$tem_currency_id]['default_to_rate'];
		$tem_price=$order['total_price']*$tem_rate;

		$tem_point=round($tem_price*PAY2POINT);
		$this->add('accumulated_point',$tem_point,'id',$order['customer_id']);
		$this->add('usable_point',$tem_point,'id',$order['customer_id']);
		// 标记订单: 已加积分
		$arr=array('point_added'=>1);
		$sales_order->update($arr,'ref_no',$ref_no);
	}
	function reduce_point_by_order($ref_no)
	{
		global $arrcurrency;
		$sales_order=new DB(Tsales_order);
		$point=new DB(Tpoint);

		$order = $sales_order->get_row($ref_no,'ref_no');
		$tem_currency_id=$order['currency_id'];
		$tem_rate=$arrcurrency[$tem_currency_id]['default_to_rate'];
		$tem_price=$order['total_price']*$tem_rate;

		$tem_point=round($tem_price*PAY2POINT);
		$this->reduce('accumulated_point',$tem_point,'id',$order['customer_id']);
		$this->reduce('usable_point',$tem_point,'id',$order['customer_id']);
		// 加回用积分购买的部分
		if($order['point_id']>0){
			$this->add('usable_point',$order['point_id'],'id',$order['customer_id']);
		}
	}
	function update_grade($id)
	{
		global $arr_grade;
		$tem = $this->get_row($id);
		$tem_point=$tem['accumulated_point'];
		$tem_grade=$tem['level'];

		$new_grade=0;
		foreach($arr_grade as $val){
			if($tem_point>=$val['start_score'] && $tem_point<=$val['end_score']){
				$new_grade=$val['level'];
			}
		}
		if($new_grade>0 && $new_grade!=$tem_grade){
			$arr=array(
				'level'=>$new_grade
			);
			$this->update($arr,'id',$id);
		}
	}
}

// end of file